import { Howl } from 'howler';

// 单例模式音频服务
class AudioService {
  constructor() {
    this.bgm = null;
    this.isPlaying = false;
    this.volume = 0.5;
    this.initialized = false;
  }

  // 初始化BGM
  init() {
    if (this.initialized) return;

    this.bgm = new Howl({
      src: ['/bgm.mp3'],
      loop: true,
      volume: this.volume,
      autoplay: false,
    });

    this.initialized = true;
    console.log('AudioService initialized');
  }

  // 播放BGM
  play() {
    if (!this.initialized) this.init();
    
    if (this.bgm && !this.isPlaying) {
      this.bgm.play();
      this.isPlaying = true;
      console.log('BGM started playing');
    }
  }

  // 暂停BGM
  pause() {
    if (this.bgm && this.isPlaying) {
      this.bgm.pause();
      this.isPlaying = false;
      console.log('BGM paused');
    }
  }

  // 切换播放/暂停
  toggle() {
    if (this.isPlaying) {
      this.pause();
    } else {
      this.play();
    }
    return this.isPlaying;
  }

  // 设置音量
  setVolume(value) {
    this.volume = value;
    if (this.bgm) {
      this.bgm.volume(value);
      console.log(`Volume set to ${value}`);
    }
  }

  // 获取当前音量
  getVolume() {
    return this.volume;
  }

  // 获取播放状态
  getPlayingStatus() {
    return this.isPlaying;
  }
}

// 导出单例实例
const audioService = new AudioService();
export default audioService; 